#coding:utf-8
import re
import json
import urllib2
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required


@login_required
def parse_video_url(request):

    #视频地址
    #    http://v.youku.com/v_show/id_XNjM1MDQ0MzA0.html
    #    http://player.youku.com/player.php/sid/XNjM1MDQ0MzA0/v.swf
    video_url = request.GET.get('url')
    reg_match = re.search(r'youku\.com\/[\w\_\.]*/(id\_|sid\/)([\w\d]*).*$', video_url)
    video_id = reg_match.group(2)
    result = {'error': True}
    if video_id:
        video_data_url = 'http://v.youku.com/player/getPlayList/VideoIDS/%s/timezone/+08/version/5/source/out?' \
                         'password=&ran=2513&n=3' % video_id
        page_data = json.loads(urllib2.urlopen(video_data_url).read())
        if 'data' in page_data:
            if len(page_data.get('data')) > 0:
                video_image = page_data.get('data')[0].get('logo')
                result = {'error': False, 'cover': video_image, 'id': video_id}

    return HttpResponse(json.dumps(result))